import React from 'react';
import PropTypes from 'prop-types';
import {Spin, Card, Button, Row, Col, Table} from 'antd';
import {DATE_FORMAT, FILES_API, TABLE} from '../constants';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import routes from './routes';
import {abandonData, submitData, getDetail} from './api';
import {injectIntl} from './intl';
import {currency, marketingActivityStatus, marketingActivityItemType, marketingActivityFundSource, marketingActivityJudgeResult} from '../Enum';
import {conventEnumValueToString, formatDateTime, formatAmount, formatPercent} from '../utils';
import {hasPermissions} from './utils';
import {PERMISSION, formatExportExcelUrl, formatExportPdfUrl} from './constants';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import styles from './style.css';
const {Description} = DescriptionList;
export class DetailPanel extends React.PureComponent {
    state = {
        loading: false,
        data: {},
    }
    componentDidMount() {
        this.getDetailInfo();
    }
    getDetailInfo = () => {
        const id = this.props.id;
        this.setState({loading: true});
        getDetail(id)
            .then(res => {
                if(res.ok)
                    this.setState({
                        loading: false,
                        data: res.data,
                        marketingActivityDetails: res.data.marketingActivityDetails.map(d => Object.assign({}, d, {
                            order: res.data.marketingActivityDetails.findIndex(x => x.id === d.id) + 1,
                        })),
                        marketingActivityApprovalRecords: res.data.marketingActivityApprovalRecords.map(d => Object.assign({}, d, {
                            order: res.data.marketingActivityApprovalRecords.findIndex(x => x.id === d.id) + 1,
                        })),
                    });
                else
                    this.setState(({
                        loading: false
                    }));
            });
    }
    handleUpdateClick = () => {
        this.props.history.push(routes.update.format(this.props.id));
    }
    handleApproveClick = () => {
        this.props.history.push(routes.approve.format(this.props.id));
    }
    handleApproveReportClick = () => {
        this.props.history.push(routes.approveReport.format(this.props.id));
    }
    handleApproveFeeClick = () => {
        this.props.history.push(routes.approveFee.format(this.props.id));
    }
    handleUploadClick = () => {
        this.props.history.push(routes.upload.format(this.props.id));
    }
    handleRegisterClick = () => {
        this.props.history.push(routes.register.format(this.props.id));
    }
    onClickAbandonBtn = () => {
        this.setState({loading: true});
        abandonData(this.state.data.id, {rowVersion: this.state.data.rowVersion})
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.successReturn();
            });
    }
    onClickSubmitBtn = () => {
        this.setState({loading: true});
        submitData(this.state.data.id, {rowVersion: this.state.data.rowVersion})
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.successReturn();
            });
    }
    onExportExcel = e => {
        e.stopPropagation();
        window.open(formatExportExcelUrl(e.currentTarget.dataset.id, e.currentTarget.dataset.code));
    }
    onExportPdf = e => {
        e.stopPropagation();
        window.open(formatExportPdfUrl(e.currentTarget.dataset.id, e.currentTarget.dataset.code));
    }
    onClickCreate = () => {
        window.open(`#/dcs/sales/CBUSaleOrder/add?piId=${this.props.id}`);
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {data, marketingActivityDetails, marketingActivityApprovalRecords} = this.state;
        const operations = [];
        const columns = [{
            title: formatMessage({
                id: 'detailPanel.column.order',
                defaultMessage: '序号'
            }),
            dataIndex: 'order',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.item',
                defaultMessage: '项目'
            }),
            dataIndex: 'item',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.itemType',
                defaultMessage: '项目类型'
            }),
            dataIndex: 'itemType',
            render: text => conventEnumValueToString(marketingActivityItemType, text)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.fundSource',
                defaultMessage: '资金来源'
            }),
            dataIndex: 'fundSource',
            render: text => conventEnumValueToString(marketingActivityFundSource, text)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.investAmount',
                defaultMessage: `投入/万${conventEnumValueToString(currency, data.currency)}`
            }),
            dataIndex: 'investAmount',
            render: text => formatAmount(text / 10000)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.supportAmount',
                defaultMessage: `支持/万${conventEnumValueToString(currency, data.currency)}`
            }),
            dataIndex: 'supportAmount',
            render: text => formatAmount(text / 10000)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.supportRatio',
                defaultMessage: '支持比例'
            }),
            dataIndex: 'supportRatio',
            render: text => formatPercent(text)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.detailRemark',
                defaultMessage: '备注'
            }),
            dataIndex: 'detailRemark',
        }];
        const approveColumns = [{
            title: formatMessage({
                id: 'detailPanel.column.approveOrder',
                defaultMessage: '审核序号'
            }),
            dataIndex: 'order',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.approverCode',
                defaultMessage: '审核人编号'
            }),
            dataIndex: 'approverCode',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.approverName',
                defaultMessage: '审核人姓名'
            }),
            dataIndex: 'approverName',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.approveResult',
                defaultMessage: '判定结果'
            }),
            dataIndex: 'approveResult',
            render: text => conventEnumValueToString(marketingActivityJudgeResult, text)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.approveTime',
                defaultMessage: '审核时间'
            }),
            dataIndex: 'approveTime',
            render: text => formatDateTime(text, DATE_FORMAT)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.approveComment',
                defaultMessage: '审核意见'
            }),
            dataIndex: 'approveComment',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.nextOperation',
                defaultMessage: '下一步操作'
            }),
            dataIndex: 'nextOperation',
        }];
        if(hasPermissions(this.props.permissions, PERMISSION.update) && hasPermissions(data.options, PERMISSION.update))
            operations.push(<Button key="update" onClick={this.handleUpdateClick} size="small">{
                formatMessage({
                    id: 'detailPage.btn.update',
                    defaultMessage: '编辑'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.abandon) && hasPermissions(data.options, PERMISSION.abandon))
            operations.push(<WrappedPopconfirm
                key="abandon"
                id={this.props.id}
                placement="topLeft"
                onConfirm={this.onClickAbandonBtn}
                title={formatMessage({
                    id: 'detailPanel.validate.abandon',
                    defaultMessage: '是否确认作废？'
                })}>
                <Button key="abandon" size="small">{
                    formatMessage({
                        id: 'detailPanel.btn.abandon',
                        defaultMessage: '作废'
                    })
                }</Button>
            </WrappedPopconfirm>);
        if(hasPermissions(this.props.permissions, PERMISSION.submit) && hasPermissions(data.options, PERMISSION.submit))
            operations.push(<WrappedPopconfirm
                key="submit"
                id={this.props.id}
                placement="topLeft"
                onConfirm={this.onClickSubmitBtn}
                title={formatMessage({
                    id: 'detailPanel.validate.submit',
                    defaultMessage: '是否确认提交？'
                })}>
                <Button key="submit" size="small">{
                    formatMessage({
                        id: 'detailPanel.btn.submit',
                        defaultMessage: '提交'
                    })
                }</Button>
            </WrappedPopconfirm>);
        if(hasPermissions(this.props.permissions, PERMISSION.upload) && hasPermissions(data.options, PERMISSION.upload))
            operations.push(<Button key="upload" onClick={this.handleUploadClick} size="small">{
                formatMessage({
                    id: 'detailPage.btn.upload',
                    defaultMessage: '上传报告和发票'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.register) && hasPermissions(data.options, PERMISSION.register))
            operations.push(<Button key="register" onClick={this.handleRegisterClick} size="small">{
                formatMessage({
                    id: 'detailPage.btn.register',
                    defaultMessage: '登记核销结果'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.approve) && hasPermissions(data.options, PERMISSION.approve))
            operations.push(<Button key="approve" onClick={this.handleApproveClick} size="small">{
                formatMessage({
                    id: 'detailPage.btn.approve',
                    defaultMessage: '审核'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.approveReport) && hasPermissions(data.options, PERMISSION.approveReport))
            operations.push(<Button key="approveReport" onClick={this.handleApproveReportClick} size="small">{
                formatMessage({
                    id: 'detailPage.btn.approveReport',
                    defaultMessage: '审核报告和发票'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.approveFee) && hasPermissions(data.options, PERMISSION.approveFee))
            operations.push(<Button key="approveFee" onClick={this.handleApproveFeeClick} size="small">{
                formatMessage({
                    id: 'detailPage.btn.approveFee',
                    defaultMessage: '审核发票和费用'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.exportExcel) && hasPermissions(data.options, PERMISSION.exportExcel))
            operations.push(<Button key="exportExcel" data-id={this.props.id} data-code={this.props.code} onClick={this.onExportExcel} size="small">{
                formatMessage({
                    id: 'detailPage.btn.exportExcel',
                    defaultMessage: '导出Excel'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.exportPdf) && hasPermissions(data.options, PERMISSION.exportPdf))
            operations.push(<Button key="exportPdf" data-id={this.props.id} data-code={this.props.code} onClick={this.onExportPdf} size="small">{
                formatMessage({
                    id: 'detailPage.btn.exportPdf',
                    defaultMessage: '导出Pdf'
                })
            }</Button>);
        return (
            <div>
                <Spin spinning={this.state.loading}>
                    <Card>
                        <DescriptionList size="large" title={<Row><Col span={12}>{formatMessage({
                            id: 'detailPanel.text.title',
                            defaultMessage: '基本信息'
                        })}</Col>
                        <Col className={`col-align-right ${styles.detail}`} span={12}>{operations}</Col>
                        </Row>}>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.brandName',
                                defaultMessage: '品牌'
                            })}>{data.brandName}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.dealerCode',
                                defaultMessage: '总代编号'
                            })}>{data.dealerCode}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.dealerName',
                                defaultMessage: '总代名称'
                            })}>{data.dealerName}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.code',
                                defaultMessage: '活动编号'
                            })}>{data.code}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.name',
                                defaultMessage: '活动名称'
                            })}>{data.name}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.country',
                                defaultMessage: '国家'
                            })}>{data.country}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.marketDepartmentName',
                                defaultMessage: '大区'
                            })}>{data.marketDepartmentName}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.totalInvestAmount',
                                defaultMessage: `总投入/万${conventEnumValueToString(currency, data.currency)}`
                            })}>{formatAmount(data.totalInvestAmount / 10000)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.totalSupportAmountSum',
                                defaultMessage: `总支持/万${conventEnumValueToString(currency, data.currency)}`
                            })}>{formatAmount(data.totalSupportAmount / 10000)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.totalSupportAmount',
                                defaultMessage: '支持比例'
                            })}>{formatPercent(data.totalSupportAmount)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.currency',
                                defaultMessage: '币种'
                            })}>{conventEnumValueToString(currency, data.currency)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.startDate',
                                defaultMessage: '活动开始日期'
                            })}>{formatDateTime(data.startDate, DATE_FORMAT)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.endDate',
                                defaultMessage: '活动结束日期'
                            })}>{formatDateTime(data.endDate, DATE_FORMAT)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.status',
                                defaultMessage: '状态'
                            })}>{conventEnumValueToString(marketingActivityStatus, data.status)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.creatorName',
                                defaultMessage: '创建人姓名'
                            })}>{data.creatorName}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.createTime',
                                defaultMessage: '创建时间'
                            })}>{formatDateTime(data.createTime, DATE_FORMAT)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.updatorName',
                                defaultMessage: '更新人姓名'
                            })}>{data.updatorName}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.updateTime',
                                defaultMessage: '更新时间'
                            })}>{formatDateTime(data.updateTime, DATE_FORMAT)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.submitterName',
                                defaultMessage: '提交人姓名'
                            })}>{data.submitterName}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.submitTime',
                                defaultMessage: '提交时间'
                            })}>{formatDateTime(data.submitTime, DATE_FORMAT)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.abandonerName',
                                defaultMessage: '作废人姓名'
                            })}>{data.abandonerName}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.abandonTime',
                                defaultMessage: '作废时间'
                            })}>{formatDateTime(data.abandonTime, DATE_FORMAT)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.remark',
                                defaultMessage: '备注'
                            })}>{data.remark}</Description>
                        </DescriptionList>
                    </Card>
                    <Card>
                        <DescriptionList size="large" title={formatMessage({
                            id: 'detailPanel.table.marketingActivityDetails',
                            defaultMessage: '市场营销活动信息清单'
                        })}>
                            <Table
                                className="white-space-nowrap"
                                columns={columns}
                                rowKey="id"
                                pagination={false}
                                dataSource={marketingActivityDetails}
                                {...TABLE} />
                        </DescriptionList>
                    </Card>
                    <Card>
                        <DescriptionList size="large" title={formatMessage({
                            id: 'detailPanel.table.marketingActivityApprovalRecords',
                            defaultMessage: '市场营销活动审核结果清单'
                        })}>
                            <Table
                                className="white-space-nowrap"
                                columns={approveColumns}
                                rowKey="id"
                                pagination={false}
                                dataSource={marketingActivityApprovalRecords}
                                {...TABLE} />
                        </DescriptionList>
                    </Card>
                    <Card>
                        {data.attachments && data.attachments.length >= 0
                            ? <DescriptionList size="large" title={formatMessage({
                                id: 'detailPanel.card.attachment',
                                defaultMessage: 'PI附件'
                            })}>
                                {data.attachments.map(item => (<Description key={item.fileId}>
                                    <a icon="download" download href={`${FILES_API.files}/${item.fileId}`} size="small">
                                        {item.fileName}</a></Description>))}
                            </DescriptionList>
                            : <DescriptionList title={formatMessage({
                                id: 'detailPanel.content.noAttachment',
                                defaultMessage: '暂无附件'
                            })}>
                            </DescriptionList>}
                    </Card>
                </Spin>
                <div className="page-toolbar">
                    <Button
                        type="primary"
                        disabled={this.state.loading}
                        onClick={this.props.onCancel}>{formatMessage({
                            id: 'detailPage.text.return',
                            defaultMessage: '返回'
                        })}</Button>
                </div>
            </div>
        );
    }
}

DetailPanel.propTypes = {
    id: PropTypes.string.isRequired,
    permissions: PropTypes.array.isRequired,
    onCancel: PropTypes.func.isRequired,
    history: PropTypes.object,
    intl: PropTypes.object,
    successReturn: PropTypes.func,
};

import {connect} from 'react-redux';
import {
    tableSearch
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);

const mapStateToProps = (state, props) => ({
    id: props.id,
    loading: state.getIn(['page', 'domainData', 'detail', 'isFetching']),
    permissions: getPermissions(state),
});
const mapDispatchToProps = (dispatch, props) => ({
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(DetailPanel));
